import os
import re
from datetime import datetime, timedelta
import tkinter as tk
from tkinter import filedialog, messagebox
from collections import Counter
import pandas as pd


def askdirectory():
    root = tk.Tk()
    root.withdraw()
    folderpath = filedialog.askdirectory(title="请选择包含.log文件的文件夹")
    return folderpath


def select_output_file_path():
    root = tk.Tk()
    root.withdraw()
    file_path = filedialog.asksaveasfilename(
        defaultextension=".xlsx",
        filetypes=[("xlsx files", "*.xlsx"), ("All files", "*.*")],
    )
    return file_path


def process_logs(folder_path, start_datetime, end_datetime):
    stats_dict = {}  # 使用字典来存储每小时的设备计数
    timestamp_pattern = re.compile(r"(\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}\.\d+)")

    for filename in os.listdir(folder_path):
        if filename.endswith(".log"):
            file_path = os.path.join(folder_path, filename)
            try:
                # 注意编码规则
                with open(file_path, "r", encoding="utf-8", errors="replace") as file:
                    lines = file.readlines()
                    # print(lines)

                # 过滤19个部分的行且最后一个部分为'1'
                matching_lines = [
                    line for line in lines if len(line.strip().split()) == 18
                ]  # and line.strip().split()[-1] == '1'
                # print(matching_lines)

                # 去除行尾的换行符和空行
                stripped_lines = [
                    line.strip() for line in matching_lines if line.strip()
                ]

                current_hour = start_datetime  # 从初始时间开始
                while current_hour < end_datetime:
                    extracted_lines = []
                    hour_start = current_hour.replace(microsecond=0)
                    print(hour_start)
                    hour_end = hour_start + timedelta(minutes=1)

                    for line in stripped_lines:
                        line_time_match = timestamp_pattern.search(line)
                        if line_time_match:
                            line_time = datetime.strptime(
                                line_time_match.group(1), "%Y-%m-%d %H:%M:%S.%f"
                            )
                            if hour_start <= line_time < hour_end:
                                extracted_lines.append(line)

                    # 统计信息
                    device_counts = Counter()
                    for line in extracted_lines:
                        parts = line.split()
                        device_counts[parts[-5][0:4]] += 1

                    # 存储结果
                    if extracted_lines:  # 只有当有匹配的行时才存储
                        stats_key = f"{current_hour.strftime('%Y-%m-%d %H:%M:%S')}-{hour_end.strftime('%H:%M:%S')}"
                        if stats_key not in stats_dict:
                            stats_dict[stats_key] = Counter()
                        stats_dict[stats_key].update(device_counts)

                    # 移动到下一个小时
                    current_hour += timedelta(minutes=1)
                    # 如果想要限制处理的时间范围，可以在这里添加逻辑来停止循环
            except Exception as e:
                print(f"Error processing file '{filename}': {e}")
        print(filename)

    # 将结果转换为列表形式（如果需要的话）
    stats_list = [{"File-Hour": k, "Devices": dict(v)} for k, v in stats_dict.items()]

    return stats_dict


def writeExcel(file_excel, time, deviceid, count):
    try:
        # 检查文件是否存在
        if not os.path.exists(file_excel):
            # 文件不存在，创建一个新的Excel文件
            df = pd.DataFrame(
                columns=["time", "device_id", "count",  "total"]
            )
            df.to_excel(file_excel, index=False)
            print("文件不存在，已创建新文件。")
            df = pd.read_excel(file_excel)
            total_count = count
            new_data = pd.DataFrame(
                {
                    "device_id": [deviceid],
                    "count": [count],
                    "total": [total_count],
                    "time": [time],
                }
            )
            # 将新数据添加到原有数据中
            df = pd.concat([df, new_data], ignore_index=True)
            # 写回Excel文件
            df.to_excel(file_excel, index=False)
            print("数据已写入。")
        else:
            # 文件存在，读取Excel文件并追加新数据
            df = pd.read_excel(file_excel)
            total_count = count
            new_data = pd.DataFrame(
                {
                    "device_id": [deviceid],
                    "count": [count],
                    "total": [total_count],
                    "time": [time],
                }
            )
            # 将新数据添加到原有数据中
            df = pd.concat([df, new_data], ignore_index=True)
            # 写回Excel文件
            df.to_excel(file_excel, index=False)
            print("数据已写入。")
    except Exception as e:
        print(f"发生错误：{e}")


def main():
    # 使用示例
    start_datetime = datetime.strptime("2025-02-20 17:36:00", "%Y-%m-%d %H:%M:%S")
    end_datetime = datetime.strptime("2025-02-20 17:42:00", "%Y-%m-%d %H:%M:%S")
    folder_path = askdirectory()
    file_excel = select_output_file_path()
    stats_list = process_logs(folder_path, start_datetime, end_datetime)
    print(stats_list)
    # tags = ["15A0","15D0","1605","1686","1746","1869",
    #         "1D59","1D89","4214","42A8","44F1","4526",
    #         "46AF","4704","488D","492A","493A","4E9D",
    #         "4EA2","5014","5110","522B","5297","52A8",
    #         "52AD","530D","5318","533A","537A","5416",
    #         "5502","5616","5686","568B","5691","5696",
    #         "56A7","56DC","579E","5809","589C","58A1"]
    # tags = ["50AD", "1D94", "4E01", "549C"]
    # tags = ['1595','1721','172D','1756','17A3','1D53','1D94','1DA4','4015','4080','40A2','41A4','420A','422B','42C6','441F','45A8','4684','4807','4E01','4E73','4EB3','4F19','501F','50A6','50AD','511B','5120','514A','528B','5347','534D','5364','53AB','53C4','549C','54A8','5534','5548','5595','55A0','55B6','562B','58B2','D18E']

    tags = ['54A8']

    for time, counter in stats_list.items():
        for tag in tags:
            count = 0
            for id, count in counter.items():
                if tag  in id:
                    count1 = count
            writeExcel(file_excel, time, tag, count1)


if __name__ == "__main__":
    main()
